package com.eqdd.yiqidian.ui.companyspace;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.RecyclerViewRefreshCustom;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.ExcellentStaffBean;
import com.eqdd.yiqidian.box.ItemDecoration.DividerLineItemDecoration;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.utils.ImageShowUtil;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import io.reactivex.Flowable;

/**
 * Created by jhj on 18-6-9.
 */

public class ExcellentStaffListActivity extends BaseActivity {

    RecyclerViewRefreshCustom dataBinding;
    private int pageNum;
    private MVCCoolHelper<List<ExcellentStaffBean>> mvcHelper;
    private SlimAdapterEx<ExcellentStaffBean> slimAdapterEx;
    private int type = 0;
    private int companyId = 0;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_recyclerview_refresh);
        initTopTitleBar(View.VISIBLE, "荣誉墙");
        type = getIntent().getIntExtra(Config.TYPE, 0);
        if (type == 0) {
            initTopRightText("新增", view -> {
                Bundle bundle = new Bundle();
                startActivityForResult(ExcellentStaffAddActivity.class, bundle, Config.ADD);
            });
            companyId = user.getCompanyId();
        } else {
            companyId = getIntent().getIntExtra(Config.COMPANY_ID, 0);
            if (companyId == 0) {
                ToastUtil.showShort("没有数据");
                finish();
            }
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public void initData() {
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.addItemDecoration(new DividerLineItemDecoration(this));
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_153, new SlimInjector<ExcellentStaffBean>() {
            @Override
            public void onInject(ExcellentStaffBean data, IViewInjector injector) {
                injector
                        .with(R.id.iv_image, view -> {
                            ImageView v = (ImageView) view;
                            if (data.getHeadImage() != null && !"".equals(data.getHeadImage())) {
                                v.setVisibility(View.VISIBLE);
                                v.setOnClickListener(view1 -> {
                                    String[] array = {data.getHeadImage()};
                                    ImageShowUtil.INSTANCE.imgPathPreview(ExcellentStaffListActivity.this, 0, Arrays.asList(array));
                                });
                                Glide.with(ExcellentStaffListActivity.this)
                                        .asBitmap()
                                        .apply(ImageUtil.optionsNormal)
                                        .load(data.getHeadImage())
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                                                double scale = (double) resource.getWidth() / (double) resource.getHeight();
                                                if (scale < 0.85 && scale > 0.65) {
                                                    v.setScaleType(ImageView.ScaleType.CENTER_CROP);
                                                    v.setImageBitmap(resource);
                                                } else {
                                                    v.setImageBitmap(resource);
                                                }
                                            }
                                        });
                            } else {
                                v.setVisibility(View.GONE);
                            }
                        })
                        .text(R.id.tv_name, String.format(Locale.CHINA, "姓名：%s", data.getTitle()))
                        .text(R.id.tv_post, String.format(Locale.CHINA, "职位：%s", data.getPost()))
                        .text(R.id.tv_msg, String.format(Locale.CHINA, "简介：%s", data.getMsg()));
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemClickSupport.addTo(dataBinding.recyclerView).setOnItemClickListener((recyclerView, position, v) -> {
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", slimAdapterEx.getDataItem(position));
            bundle.putInt(Config.TYPE, type);
            startActivityForResult(ExcellentStaffInfoActivity.class, bundle, Config.UPDATE);
        });


        ModelRx2DataSource<ExcellentStaffBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
            @Override
            public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                pageNum = page == 1 ? 0 : pageNum;
                return OkGo.<HttpResult<List<ExcellentStaffBean>>>post(HttpConfig.BASE_URL + HttpConfig.EXCELLENT_STAFF_LIST)
                        .params("companyId", companyId)
                        .params("page", pageNum)
                        .converter(new JsonConverter<HttpResult<List<ExcellentStaffBean>>>() {
                            @Override
                            public void test() {
                                super.test();
                            }
                        }).adapt(new FlowableBody<>())
                        .flatMap(result -> {
                            if (page == 1) {
                                mvcHelper.setAutoLoadMore(true);
                            }
                            pageNum = result.getPage();
                            return Flowable.just(result.getItems() == null ? new ArrayList() : result.getItems());
                        });
            }
        }, 1000);
        mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAdapter(slimAdapterEx);
        mvcHelper.refresh();


    }

    @Override
    public void setView() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Config.ADD && resultCode == RESULT_OK) {
            mvcHelper.refresh();
        }
        if (requestCode == Config.UPDATE && resultCode == RESULT_OK) {
            mvcHelper.refresh();
        }
    }
}
